package com.reminder;

import java.util.List;

import com.reminder.shared.ReminderRequestFactory;
import com.reminder.shared.ReminderRequest;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.ServerFailure;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AcceptInvite extends ListActivity implements Runnable{
	    public  static ArrayAdapter <String> adapter;
	    private List<String> inviteEmails; 
	    								//THIS LIST IS GETTING INITIALIZED IN THE getNewInvites() function
	    								//which is called from the run() function
	    private String acceptedEmail;
	    
		  /** Called when the activity is first created. */
		     @Override
		     public void onCreate(Bundle savedInstanceState) {
		         super.onCreate(savedInstanceState);
		         setContentView(R.layout.loading);
		         Thread thread = new Thread(this);
		         thread.start(); //start the thread to get the list of the invites
		     }
		     
		     private Handler mHandler = new Handler(){
		    	 public void handleMessage(Message msg){
		    		setAdapter(); //once all the invites are loaded from the database we can go ahead and set the adapter to display the recieved list of the invites
		    	 }
		     };
		     
		     public void run() {
		    	 getNewInvites();		//HERE we call getNewInvites() which is going to set the inviteEmails list
		    	 mHandler.sendEmptyMessage(0); 
		    	 //the list has been loaded from the database so we then now are going to go the  handleMessage() function,
		    	 //and call the setAdapter() from there to get the list to be displayed
		     }

		  protected void onListItemClick(ListView l, View v, int position, long id) { //this function is called when the user clicks on the check box next to the invite
		   super.onListItemClick(l, v, position, id);
		   acceptedEmail = inviteEmails.get(position);
		   inviteEmails.remove(position); //remove the accepted invite from the local list
		   onAcceptClick(); //this function is going to update the db to reflect the fact that user has accepted the invite
		   Toast.makeText(this,"you accepted the invitation from the user " + acceptedEmail, Toast.LENGTH_SHORT).show();		  
		  }
		  
		 public void getNewInvites() { //gets the list of invites from the db
		  	ReminderRequestFactory factory = (ReminderRequestFactory) Util
		              .getRequestFactory(AcceptInvite.this,
		                      ReminderRequestFactory.class);
		      ReminderRequest request = factory.taskRequest();
		      request.getInvitesNotAccepted().fire(new Receiver<List<String>>() {
					@Override
					public void onSuccess(List<String> result) {
						// if success
						inviteEmails = result;
						//setAdapter();
					}
					
					@Override
					public void onFailure(ServerFailure failure) {
						// If error
					}
				});
		 }
			      
		     
		 public void setAdapter(){
			 if (!inviteEmails.isEmpty()){
			 adapter = new ArrayAdapter<String>(this,android.R.layout.select_dialog_multichoice,inviteEmails); //pass the inviteEmails list to the adapter
	         getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
	         setListAdapter(adapter);
			 }
			 else {
				 Toast.makeText(this,"You have no pending invitations ", Toast.LENGTH_SHORT).show();
			 }
				 
				 
		 }
		 
		 public void onAcceptClick() {
		    	new AsyncTask<Void, Void, Void>() {

		            @Override
		            protected Void doInBackground(Void... arg0) {
		    	ReminderRequestFactory factory = (ReminderRequestFactory) Util
		                .getRequestFactory(AcceptInvite.this,
		                        ReminderRequestFactory.class);
		        ReminderRequest request = factory.taskRequest();
		        //request.createUserGroup(acceptedEmail).fire();
		        request.updateUserGroupInviteToTrue(acceptedEmail).fire(); //going to the db to update the records to reflect the fact that the user has accepted the invitation
		        return null;
		            }

		        }.execute();
		   }

		}
